package com.lzq.shiro.config.util;



import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import com.lzq.shiro.config.Constant;
import com.lzq.shiro.config.MyShiroRealm;
import com.lzq.shiro.entity.UserInfo;

/**
 * @author Administrator
 * @title shiro工具类
 */
public class ShiroUtil {
	
	
	
	
	
	/**
	 * @title 通过sessionId判断用户是否处于登录状态
	 * @param sessionId
	 * @param request
	 * @param response
	 * @return
	 */
	public static boolean isAuthenticated(String sessionId , HttpServletRequest request , HttpServletResponse response) {
		
		boolean status = false;
		// 如果没有传入sessionId,尝试从cookies中获取
		if(StringUtils.isBlank(sessionId)) {
			Cookie cookies[] = request.getCookies();
			if(cookies != null && cookies.length > 0) {				
				for(Cookie cookie : cookies) {
					String cookieName = cookie.getName();
					if(Constant.SHIRO_COOKIE_NAME.equals(cookieName)) {
						sessionId = cookie.getValue();
					}
				}
			}
		}
		try {
			SessionKey key = new WebSessionKey(sessionId , request , response);
			Session session = SecurityUtils.getSecurityManager().getSession(key);
			Object obj = session.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
			if(obj != null) {
				status = (Boolean) obj;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return status;
	}
	
	
	/**
	 * @title 通过sessionId获取用户信息
	 * @param sessionId
	 * @param request
	 * @param response
	 * @return
	 */
	public static UserInfo getUserInfo(String sessionId , HttpServletRequest request , HttpServletResponse response) {
		try {
			SessionKey key = new WebSessionKey(sessionId , request , response);
			Session session = SecurityUtils.getSecurityManager().getSession(key);
			Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
			return (UserInfo) coll.getPrimaryPrincipal();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		return null;
	}

	
	
	/**
	 * @title 刷新用户权限
	 * @param principal
	 * @desc principal为用户的认证信息
	 */
	public static void  reloadAuthorizing(Object principal) throws Exception{
		RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
		MyShiroRealm myShiroRealm = (MyShiroRealm) rsm.getRealms().iterator().next();

		Subject subject = SecurityUtils.getSubject();
		String realmName = subject.getPrincipals().getRealmNames().iterator().next();
		// 第一个参数为用户信息 ， 第二个参数为realmName 
		// 注意：参数principal对象生成的缓存key必须与redis中的一致，否则将会导致匹配不上，权限更新失败，这里的key生成规则在ShiroRedisCache中定义的，即authority:mobile
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, realmName);
		subject.runAs(principals);
		if(myShiroRealm.isAuthenticationCachingEnabled()) {					
			myShiroRealm.getAuthenticationCache().remove(principals);
		}
		if(myShiroRealm.isAuthorizationCachingEnabled()) {
			// 删除指定用户shiro权限
			myShiroRealm.getAuthorizationCache().remove(principals);
		}
		subject.releaseRunAs();
	}
	
	
	
	
}
